import base64
import pickle

from django_redis import get_redis_connection


def merge_cookie_cart_to_redis(request, user, response):
    """合并cookie中的购物车数据到redis数据库中"""
    # 获取cookie中的购物车数据
    cookie_cart = request.COOKIES.get('cart') # None

    if cookie_cart is None:
        # cookie购物车无数据,直接返回
        return

        # 解析cookie中的购物车数据

        # {
        # '<sku_id>':{
        #     'count':<count>,
        #     'selected':'<selected>'
        #     }
        #     ...
        # }
        #
    cart_dict = pickle.loads(base64.b64decode(cookie_cart))
    if not cart_dict:
        # 字典为空,购物车无数据,直接返回
        return

    # 保存cookie购物车中添加的商品的id和对应的数量count
    cart = {}

    # 保存cookie购物车中被勾选的商品id,次列表中的元素进行购物车记录合并时需要添加到redis set中
    cart_selected_add = []

    # 保存cookie购物车中未被勾选的商品的id,此列表中的元素在进行购物车合并时需要添加redis set中移除
    cart_selected_remove = []
    for sku_id, count_selected in cart_dict.items():
        cart[sku_id] = count_selected['count']

        if count_selected['selected']:
            cart_selected_add.append(sku_id)

        else:
            cart_selected_remove.append(sku_id)

    # 运行合并
    redis_conn = get_redis_connection('cart')

    # 合并redis hash中合并商品的id和数量
    cart_key = 'cart_%s' % user.id
    redis_conn.hmset(cart_key, cart)

    # 向redis set 中合并勾选状态
    cart_selected_key = 'cart_select_%s' % user.id

    if cart_selected_add:
        redis_conn.sadd(cart_selected_key, *cart_selected_add)

    if cart_selected_remove:
        srem = redis_conn.srem(cart_selected_key, *cart_selected_remove)

    # 清除购物车数据
    response.delete_cookie('cart')

